package com.supply.dl.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.supply.dl.R;
import com.supply.dl.app.http.BaseInfo;
import com.supply.dl.http.HttpManger;
import com.supply.dl.utils.ImageUtil;
import com.supply.dl.utils.PhotoUtils;
import com.supply.dl.utils.StringUtils;
import com.supply.dl.utils.utils.FileUtils;
import com.supply.dl.utils.utils.ToastUtil;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.io.File;
import java.util.Iterator;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicLong;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * <p>Activity基类(项目中的所有Activity都继承自此类)</p>
 * <p>time 2014/10/25</p>
 *
 * @version CmgeForum 1.0.0
 */
public abstract class BaseActivity extends RxAppCompatActivity implements View.OnClickListener,HttpManger.HttpResponseCallBackListener {
    /**
     * 配置信息的KEY
     */
    public static final String KEY_CONFIGURE = "configure";
    /**
     * 登录信息的KEY
     */
    public static final String KEY_LOGIN = "login";
    /**
     * 登录信息的KEY
     */
    public static final String KEY_LOGIN_USER_INFO = "userInfo";
    /**
     * 配置的时间差的KEY
     */
    public static final String KEY_TIME = "time";
    /**
     * 登录状态的KEY
     */
    public static final String KEY_LOGIN_STATUS = "login_status";
    /**
     * 当前已有的Activity集合
     */
    protected static Stack<BaseActivity> activityList = new Stack<BaseActivity>();
    /**
     * 子线程与主线程的通信用的mHandler
     */
    protected Handler mHandler = new Handler();
    /**
     * 是否执行了onDestroy
     */
    private boolean isDestroy = false;
    /**
     * onDestroy是否取消Toast
     */
    protected boolean isDestroyToast = true;
    /**
     * 记录之前显示过的Toast
     */
    private Toast mToast;

    protected BaseActivity mActivity;

    /**
     * 默认的标题
     */
    protected CharSequence defaultTitle;

    /**
     * 点击登录的统计的页面EventID
     */
    private String statisticsLoginEventID;

    /**
     * 是否启动activity动画
     */
    private boolean isStartAnim = true;

    /**
     * 标题点击
     */
    private Runnable onTitleClickListener;

    private boolean mResume;

    /**
     * 记录进入的时间
     */
    public static AtomicLong inTime = new AtomicLong();


    /**
     * 顶部栏
     */
    @BindView(R.id.toolbar)
    protected Toolbar toolbar;

    /**
     * 内容
     */
    private FrameLayout content_base;

    /**
     * 标题title的显示
     */
    @BindView(R.id.common_title_main_titleName)
    protected TextView title_tv;

    /**
     * 右边文本控件
     */
    @BindView(R.id.common_title_main_rightTv)
    protected TextView right_tv;

    @BindView(R.id.common_title_main_backImg)
    protected ImageView back_img;

    /**
     * home图标
     */
    @BindView(R.id.common_title_main_homeImg)
    protected ImageView home_img;

    /**
     * 二维码图标
     */
    @BindView(R.id.common_title_main_scanImg)
    protected ImageView scan_img;

    protected final int HEAD_ABLUME=1;// 相册
    protected final int HEAD_CAREAM=2;// 相机

    public static int getActivityStackSize() {
        return activityList.size();
    }

    public String getStatisticsLoginEventID() {
        return statisticsLoginEventID;
    }

    public void setStatisticsLoginEventID(String statisticsLoginEventID) {
        this.statisticsLoginEventID = statisticsLoginEventID;
    }

    public void setOnTitleClickListener(Runnable onTitleClickListener) {
        this.onTitleClickListener = onTitleClickListener;
    }

    /**
     * 添加activity到管理集合中
     *
     * @param activity 要添加的activity
     */
    protected static synchronized void addActivity(BaseActivity activity) {
        if (null != activity && !activityList.contains(activity)) {
            activityList.add(activity);
        }
    }

    /**
     * 从管理集合中删除activity
     *
     * @param activity 要移除的activity
     */
    protected static synchronized void removeActivity(BaseActivity activity) {
        if (null != activity && activityList.contains(activity)) {
            activityList.remove(activity);
        }
    }

    /**
     * 移除所有的Activity实例
     */
    protected static synchronized void removeAllActivity() {
        activityList.clear();
    }

    /**
     * 退出所有activity并退出
     */
    public static synchronized void exitAllActivity() {
        Iterator<BaseActivity> it = activityList.iterator();
        while (it.hasNext()) {
            BaseActivity activity = it.next();
            if (null != activity && !activity.isFinishing()) {
                activity.finish(false);
            }
            it.remove();
        }
    }

    /**
     * 退出所有activity并退出
     */
    public static synchronized void exitAllActivity(Class<? extends BaseActivity> saveBaseActivity) {
        Iterator<BaseActivity> it = activityList.iterator();
        while (it.hasNext()) {
            BaseActivity activity = it.next();
            if (null != activity && !activity.isFinishing()) {
                String name = ((Object) activity).getClass().getName();
                if (!name.equals(saveBaseActivity.getName())) {
                    activity.finish(false);
                    it.remove();
                }
            }
        }
    }

    /**
     * 关闭指定的页面
     */
    public static synchronized void exitNamedActivity(Class<? extends BaseActivity> clazz, BaseActivity saveBaseActivity) {
        Iterator<BaseActivity> it = activityList.iterator();
        while (it.hasNext()) {
            BaseActivity activity = it.next();
            if (activity != saveBaseActivity) {
                if (null != activity && !activity.isFinishing()) {
                    String name = ((Object) activity).getClass().getName();
                    if (name.equals(clazz.getName())) {
                        activity.finish(false);
                        it.remove();
                    }
                }
            }
        }
    }

    /**
     * 关闭指定的页面
     */
    public static synchronized void exitActivity(Class<? extends BaseActivity> clazz) {
        Iterator<BaseActivity> it = activityList.iterator();
        while (it.hasNext()) {
            BaseActivity activity = it.next();
            if (null != activity && !activity.isFinishing()) {
                String name = ((Object) activity).getClass().getName();
                if (name.equals(clazz.getName())) {
                    activity.finish(false);
                    it.remove();
                }
            }
        }
    }

    /**
     * 验证activityList里是否存在指定的页面
     *
     * @param clazz clazz
     * @return 有，返回true, 没有false
     */
    public static synchronized boolean containsActivity(Class<? extends BaseActivity> clazz) {
        for (BaseActivity activity : activityList) {
            if (null != activity && !activity.isFinishing()) {
                String name = ((Object) activity).getClass().getName();
                if (name.equals(clazz.getName())) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 关闭其他的页面，保留指定的页面
     */
    public static synchronized void finishAllActivityExceptAppointed(Class<?> notFinishActivity) {
        for (Activity activity : activityList){
            if (!activity.isFinishing() && !activity.getClass().getName().equals(notFinishActivity.getName())) {
                activity.finish();
            }
        }
    }

    public void post(Runnable mRunnable) {
        if (!isDestroy()) {
            mHandler.post(mRunnable);
        }
    }

    public void postDelayed(Runnable mRunnable, long delayMillis) {
        if (!isDestroy()) {
            mHandler.postDelayed(mRunnable, delayMillis);
        }
    }

    @Override
    public void onBackPressed() {
        try {
            super.onBackPressed();
        } catch (Exception ignored) {
        }
    }

    public final boolean isResume() {
        return mResume;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

    }

    @Override
    public void setContentView(int layoutResId) {
        try {
            super.setContentView(layoutResId);
        } catch (Error e) {
            System.gc();
            super.setContentView(layoutResId);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mResume = true;
        onPageStart();
    }

    protected void onPageStart() {
        if (TextUtils.isEmpty(defaultTitle))
            return;
    }

    protected void onPageEnd() {
        if (TextUtils.isEmpty(defaultTitle))
            return;
    }

    @Override
    protected void onPause() {
        super.onPause();
        mResume = false;
        onPageEnd();
    }

    private static int ADV_COUNT = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_base);

        content_base = findViewById(R.id.content_base);
        content_base.addView(LayoutInflater.from(this).inflate(getLayoutResource(), null));
        ButterKnife.bind(this);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        initView();
        initLoadingView();
        initListener();
        initData(savedInstanceState);
        initRecyclerView();
        addActivity(this);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 设置Toolbar不可见
     */
    public void setToolBarInVisable() {
        toolbar.setVisibility(View.GONE);
    }


    /**
     * 设置Toolbar可见
     */
    public void setToolBarVisable() {
        toolbar.setVisibility(View.VISIBLE);
    }

    /**
     * 设置标题的显示
     *
     * @param title
     */
    protected void setTitleShow(String title) {
        title_tv.setText(title);
    }

    /**
     * 设置右边布局 不可见
     */
    protected void setRightInVisible() {
        right_tv.setVisibility(View.GONE);
        home_img.setVisibility(View.GONE);
        scan_img.setVisibility(View.GONE);
    }


    /**
     * 设置标题返回
     */
    protected void showLeftBack() {
        back_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 设置标题返回
     *
     * @param onClickListener
     */
    protected void showLeftBack(View.OnClickListener onClickListener) {
        if (onClickListener == null)
            showLeftBack();

        back_img.setOnClickListener(onClickListener);
    }

    /**
     * 给toolbar设置返回按钮
     */
//    protected void showLeftBack() {
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//    }

    /**
     * 显示右边的文本，并且设置监听
     *
     * @param rightContentText
     * @param onClickListener
     */
    protected void showRightText(String rightContentText, View.OnClickListener onClickListener) {
        right_tv.setText(rightContentText);
        right_tv.setVisibility(View.VISIBLE);
        home_img.setVisibility(View.GONE);
        scan_img.setVisibility(View.GONE);

        if (onClickListener != null)
            right_tv.setOnClickListener(onClickListener);
    }

    /**
     * 设置home图标点击事件
     *
     * @param onClickListener
     */
    protected void setRightHomeClick(View.OnClickListener onClickListener) {
        if (onClickListener != null) {
            home_img.setOnClickListener(onClickListener);
        }
    }

    /**
     * 设置扫码图标点击事件
     *
     * @param onClickListener
     */
    protected void setRightScanClick(View.OnClickListener onClickListener) {
        if (onClickListener != null) {
            scan_img.setOnClickListener(onClickListener);
        }
    }

    /**
     * .
     * 跳转页面,并且保留当前页面
     *
     * @param cls
     */
    public void jumpActivity(Class<? extends BaseActivity> cls) {
        Intent intent = new Intent(this, cls);
        startActivity(intent);
    }

    /**
     * 携带数据跳转页面,并且保留当前页面
     *
     * @param cls
     * @param bundle
     */
    public void jumpActivity(Class<? extends BaseActivity> cls, Bundle bundle) {
        Intent intent = new Intent(this, cls);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 跳转页面，关闭当前页面
     *
     * @param cls
     */
    public void skipActivity(Class<? extends BaseActivity> cls) {
        Intent intent = new Intent(this, cls);
        startActivity(intent);
        finish();
    }

    /**
     * 跳转页面，关闭当前页面
     *
     * @param cls
     */
    public void skipActivity(Class<? extends BaseActivity> cls, Bundle extras) {
        Intent intent = new Intent(this, cls);
        intent.putExtras(extras);
        startActivity(intent);
        finish();
    }

    public String getResourcesString(int resId) {
        return getResources().getString(resId);
    }

    protected abstract int getLayoutResource();

    protected void initView() {
    }

    protected void initListener() {
    }

    protected void initData(Bundle savedInstanceState) {
    }

    protected void initRecyclerView() {
    }

    protected void initLoadingView() {
    }


    protected void onCreate(Bundle arg0, boolean hasTitle) {
        isDestroy = false;
        mActivity = this;
    }

    protected boolean isEnabledAdv() {
        return true;
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        isDestroy = true;
        try {
            super.onDestroy();
        } catch (Exception ignored) {

        }
    }

    public boolean isDestroyToast() {
        return isDestroyToast;
    }

    public void setDestroyToast(boolean isDestroyToast) {
        this.isDestroyToast = isDestroyToast;
    }

    /**
     * 返回当前的Activity是否销毁
     *
     * @return 销毁结果
     */
    public boolean isDestroy() {
        return isDestroy;
    }

    public void showToast(int rId) {
        showToast(getResources().getString(rId), Toast.LENGTH_SHORT);
    }

    public void showToast(CharSequence text) {
        showToast(text, Toast.LENGTH_SHORT);
    }

    /**
     * 用Toast显示提示
     *
     * @param text     要提示的文字
     * @param duration see Toast.LENGTH_LONG Toast.LENGTH_SHORT
     */
    public void showToast(final CharSequence text, final int duration) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (mToast != null) {
                    mToast.cancel();
                }
                mToast = Toast.makeText(BaseActivity.this, text, duration);
                mToast.show();
            }
        });
    }

    public void cancelToast() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (mToast != null) {
                    mToast.cancel();
                }
            }
        });
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        if (isStartAnim)
            overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_from_left);
    }

    public boolean isStartAnim() {
        return isStartAnim;
    }

    public void setStartAnim(boolean isStartAnim) {
        this.isStartAnim = isStartAnim;
    }
/*@Override
    public void startActivityForResult(Intent intent, int requestCode)
	{
		super.startActivityForResult(intent, requestCode);
		overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_from_left);
	}*/

    @SuppressLint("RestrictedApi")
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
        super.startActivityForResult(intent, requestCode, options);
        if (isStartAnim)
            overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_from_left);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        if (isStartAnim)
            overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_from_left);
    }

    @Override
    public void finish() {
        finish(true);
    }

    protected void finish(boolean isAnim) {
        super.finish();
        if (isAnim) {
            overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_from_right);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    protected static final int CODE_GALLERY_REQUEST = 0xa0;
    protected static final int CODE_CAMERA_REQUEST = 0xa1;
    protected static final int CODE_RESULT_REQUEST = 0xa2;
    private static final int CAMERA_PERMISSIONS_REQUEST_CODE = 0xa3;
    private static final int STORAGE_PERMISSIONS_REQUEST_CODE = 0xa4;
    private static final int OUTPUT_X = 480;
    private static final int OUTPUT_Y = 480;

    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
    protected Uri imageUri;
    private Uri cropImageUri;
    /**
     * 动态申请权限的结果
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            //调用系统相机申请拍照权限回调
            case CAMERA_PERMISSIONS_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (hasSdcard()) {
                        imageUri = Uri.fromFile(fileUri);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            imageUri = FileProvider.getUriForFile(BaseActivity.this, "com.zz.fileprovider", fileUri);//通过FileProvider创建一个content类型的Uri
                        PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
                    } else {
                        ToastUtil.showToast(this, "设备没有SD卡！");
                    }
                } else {
                    ToastUtil.showToast(this, "请允许打开相机！！");
                }
                break;
            //调用系统相册申请Sdcard权限回调
            case STORAGE_PERMISSIONS_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
                } else {
                    ToastUtil.showToast(this, "请允许打操作SDCard！！");
                }
                break;
        }
    }

    /**
     * 自动获取sdk权限
     */
    protected void autoObtainStoragePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSIONS_REQUEST_CODE);
        } else {
            PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
        }
    }
    /**
     * 自动获取相机权限
     */
    protected void autoObtainCameraPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                ToastUtil.showToast(this, "您已经拒绝过一次");
            }
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, CAMERA_PERMISSIONS_REQUEST_CODE);
        } else {//有权限直接调用系统相机拍照
            if (hasSdcard()) {
                imageUri = Uri.fromFile(fileUri);
                //通过FileProvider创建一个content类型的Uri
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageUri = FileProvider.getUriForFile(BaseActivity.this, "com.zz.fileprovider", fileUri);
                }
                PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
            } else {
                ToastUtil.showToast(this, "设备没有SD卡！");
            }
        }
    }

    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onSuccess(BaseInfo<?> baseInfo) {

    }

    @Override
    public void onFailure(String message) {

    }

    /**
     * 将字符串为空的数据，默认为""
     * @param string
     * @return
     */
    protected String getStringByIsEmpty(String string){
        if (StringUtils.isEmpty(string)){
            return "";
        }
        return string;
    }

    /**
     * 获取xml的字符串内容
     * @param resId
     * @return
     */
    protected String getStringByResId(int resId){
        return getResources().getString(resId);
    }

    /**
     * api 19以后
     * 4.4版本后 调用系统相机返回的不在是真实的uri 而是经过封装过后的uri，
     * 所以要对其记性数据解析，然后在调用displayImage方法尽心显示
     *
     * @param data
     */

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    protected String handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            //如果是document类型的uri 则通过id进行解析处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                //解析出数字格式id
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = ImageUtil.getImagePath(BaseActivity.this, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("" +
                        "content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = ImageUtil.getImagePath(BaseActivity.this, contentUri, null);
            }
        } else if ("content".equals(uri.getScheme())) {
            //如果不是document类型的uri，则使用普通的方式处理
            imagePath = ImageUtil.getImagePath(BaseActivity.this, uri, null);
        }
//        displayImage(imagePath);
        return imagePath;
    }


    /**
     * 4.4版本一下 直接获取uri进行图片处理
     *
     * @param data
     */
    protected String handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = ImageUtil.getImagePath(BaseActivity.this, uri, null);
        return imagePath;
//        displayImage(imagePath);
    }

    protected void displayImage(String path){

    }

}
